package com.example.yudaoly.web.controller;


import com.example.yudaoly.domain.vo.AuthLoginReqVO;
import com.example.yudaoly.domain.vo.AuthLoginRespVO;
import com.example.yudaoly.domain.vo.ResponseResult;
import com.example.yudaoly.security.LoginUser;
import com.example.yudaoly.service.UsersService;
import com.example.yudaoly.utils.JwtUtil;
import com.example.yudaoly.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin-api/system")
public class LoginController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UsersService usersService;
    @PostMapping("/auth/login")
    public ResponseResult<AuthLoginRespVO> doLogin(@RequestBody @Valid AuthLoginReqVO reqVO){
        AuthLoginRespVO respVO = new AuthLoginRespVO();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(reqVO.getUsername(),reqVO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUsers().getId().toString());
        List<String> list = usersService.findPermsByUserId(loginUser.getUsers().getId());
        loginUser.setPerms(list);
        respVO.setJwt(jwt);
        respVO.setUserId(loginUser.getUsers().getId());
        respVO.setExpiresTime(LocalDateTime.now());
        //登录成功后，往Redis中加入一条数据
        redisCache.setCacheObject("login:"+loginUser.getUsers().getId(),loginUser,2, TimeUnit.MINUTES);
        return new ResponseResult<>(200,jwt,respVO);
    }

    @PostMapping("/doLogout")
    public ResponseResult<String> doLogout(){

        usersService.logout();

        return new ResponseResult<>(HttpStatus.OK.value(),"登出成功");
    }
}
